<?php

namespace common\models\base;

use Yii;
use yii\helpers\ArrayHelper;

/**
 * This is the model class for table "{{%base_dist}}".
 *
 * @property int $id
 * @property string $name 名称
 * @property string $code 区号代码
 * @property string $abbr
 * @property int $level
 * @property int $parent_id
 */
class BaseDist extends \common\db\ActiveRecord {

    /**
     * {@inheritdoc}
     */
    public static function tableName() {
        return '{{%base_district}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules() {
        return [
            [['code'], 'required'],
            [['level', 'parent_id'], 'integer'],
            [['name'], 'string', 'max' => 50],
            [['code'], 'string', 'max' => 6],
            [['abbr'], 'string', 'max' => 20],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels() {
        return [
            'id' => 'ID',
            'name' => '名称',
            'code' => '区号代码',
            'abbr' => 'Abbr',
            'level' => 'Level',
            'parent_id' => 'Parent ID',
        ];
    }

    public static function getUnifinedName($code, $split = ' ') {
        $areaCode = array_unique($code);
        $data = [];
        Yii::error($areaCode, __METHOD__);
        if (!empty($areaCode)) {
            $rec = static::find()
            ->where(['code' => $areaCode])
            ->orderBy(['level' => SORT_ASC])
            ->all();

            $data = ArrayHelper::map($rec, 'code', 'name');
            Yii::error($data, __METHOD__);
        }
        if ($split !== false) {
            return implode('、', $data);
        }
        return $data;
    }

    public static function getList($level = 1, $parentnode = 0, $parentnodetype = 'code', $returnkey = 'code') {

        $nodelist = [];
        if ($parentnode) {
            $parent = static::findOne(['level' => $level, $parentnodetype => $parentnode]);
            if (!empty($parent)) {
                $source = static::findAll(['level' => $level + 1, 'parent_id' => $parent->id]);
                $nodelist = ArrayHelper::map($source, ($returnkey ? $returnkey : 'id'), 'name');
            }
        } else {
            $nodelist = ArrayHelper::map(static::findAll(['level' => $level]), ($returnkey ? $returnkey : 'id'), 'name');
        }
        return $nodelist;
    }

}
